import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/index'
import wechatAuth from '@/utils/wechatAuth'

Vue.use(Router)

const routes = [
  {
    path: '*',
    redirect: '/goods'
  },
  {
    name: 'user',
    component: () => import('./view/user'),
    meta: {
      title: '会员中心'
    }
  },
  {
    name: 'cart',
    component: () => import('./view/cart'),
    meta: {
      title: '购物车'
    }
  },
  {
    name: 'goods',
    component: () => import('./view/goods'),
    meta: {
      title: '商品详情'
    }
  }
]

// add route path
routes.forEach(route => {
  route.path = route.path || '/' + (route.name || '')
})

const router = new Router({ routes })

router.beforeEach((to, from, next) => {
  const title = to.meta && to.meta.title
  if (title) {
    document.title = title
  }
  // 微信授权
  let loginStatus = ~~localStorage.getItem('loginStatus') || 0
  if (process.env.NODE_ENV === 'development') loginStatus = 2

  store.commit('setLoginStatus', loginStatus)

  if (store.state.loginStatus === 0) {
    // 微信未授权登录跳转到授权登录页面
    if (router.mode === 'hash') {
      const url = window.location.href.split('#')
      localStorage.setItem('historyUrl', url[1])
      wechatAuth.redirectUri = url[0]
    } else if (router.mode === 'history') {
      wechatAuth.redirectUri = window.location.href
    }

    store.dispatch('setLoginStatus', 1)
    window.location.href = wechatAuth.authUrl
  } else if (store.state.loginStatus === 1) {
    try {
      wechatAuth.returnFromWechat(location.search)
    } catch (err) {
      store.dispatch('setLoginStatus', 0)
    }
    store
      .dispatch('loginWechatAuth', wechatAuth.code)
      .then(res => {
        console.log(res)
        if (res.errcode === 0 && res.data.sign) {
          store.dispatch('setLoginStatus', 2)
          localStorage.setItem('wx_sign', res.data.sign)
          localStorage.setItem('sign_expire', res.data.expire)
          // console.log('sign存储成功', res.data.sign)
          const url = localStorage.getItem('historyUrl')
          localStorage.removeItem('historyUrl')
          window.location.href = window.location.href.split('?')[0] + '#' + url
        } else {
          store.dispatch('setLoginStatus', 0)
          // console.log('sign存储失败')
        }
        localStorage.setItem('author_refush_time', true)
      })
      .catch(err => {
        // console.log('sign请求失败')
        console.warn(err)
        localStorage.setItem('author_refush_time', true)
      })
  } else {
    if (+localStorage.getItem('sign_expire') < Date.now()) {
      store.dispatch('setLoginStatus', 0)
      // 授权失败刷新页面重新授权，防止无限刷新
      var flag = localStorage.getItem('author_refush_time')
      if (flag) {
        localStorage.setItem('author_refush_time', false)
        window.location.reload()
      }
    }
  }
  next()
})

export default router
